﻿using System.Net;
using System.Runtime.Serialization;

namespace Ping.Core
{
	/// <summary>
	/// An IPAddress replacement that can actually be serialized, even under windows phone.
	/// </summary>
	/// <remarks>
	/// This class is not threadsafe at all.
	/// </remarks>
	[DataContract]
	public sealed class IpAddress
	{
		[DataMember] internal string Data;

		private IPAddress _address;

		/// <summary>
		/// Creates an empty IpAddress.
		/// </summary>
		public IpAddress()
		{
		}

		/// <summary>
		/// Creates an IpAddress from the given IPAddress (the .net framework version).
		/// </summary>
		/// <param name="address"></param>
		public IpAddress(IPAddress address)
		{
			if (address != null)
				Data = address.ToString();

			_address = address;
		}

		public IPAddress Native
		{
			get
			{
				if (_address == null)
					_address = IPAddress.Parse(Data);

				return _address;
			}
		}

		public static IpAddress Parse(string address)
		{
			return new IpAddress(IPAddress.Parse(address));
		}

		public override bool Equals(object obj)
		{
			if (!(obj is IpAddress))
				return false;

			return Data.Equals(((IpAddress) obj).Data);
		}

		public override int GetHashCode()
		{
			return Data.GetHashCode();
		}

		public bool IsValid
		{
			get
			{
				if (Data == null)
					return false;

				IPAddress unused;
				return IPAddress.TryParse(Data, out unused);
			}
		}

		public override string ToString()
		{
			return IsValid
			       	? Native.ToString()
			       	: "n/a";
		}
	}
}